package com.op.parcel.manage.config.security.authentication;

import com.op.parcel.common.api.R;
import com.op.parcel.manage.config.security.util.HttpDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xuan🐽
 */
@Slf4j
@Component
public class FailureHandler extends SimpleUrlAuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
		if (e instanceof BadCredentialsException ||
			e instanceof UsernameNotFoundException) {
			HttpDataUtil.respJson(response, R.error("账户名或者密码输入错误"));
		} else if (e instanceof LockedException) {
			HttpDataUtil.respJson(response, R.error("账户被锁定，请联系管理员"));
		} else if (e instanceof CredentialsExpiredException) {
			HttpDataUtil.respJson(response, R.error("密码过期，请联系管理员"));
		} else if (e instanceof AccountExpiredException) {
			HttpDataUtil.respJson(response, R.error("账户过期，请联系管理员"));
		} else if (e instanceof DisabledException) {
			HttpDataUtil.respJson(response, R.error("账户被禁用，请联系管理员"));
		} else {
			HttpDataUtil.respJson(response, R.error("登录失败，其他内部错误"));
		}
	}

}
